package com.stevenmoon.csdnplus.presenter.base;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;

import java.lang.ref.WeakReference;

import rx.subscriptions.CompositeSubscription;

/**
 * 不使用{@link MvpBasePresenter}的手动检查非空的presenter父类
 * 注意！需要自己在detachView里取消后台操作，否则会导致NullPointerException
 * Created by WangJun on 2016/4/9.
 */
public class MvpBaseNoCheckPresenter<V extends MvpView> implements MvpPresenter<V> {


    private CompositeSubscription mCompositeSubscription;

    public CompositeSubscription getCompositeSubscription() {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }

        return this.mCompositeSubscription;
    }

    private WeakReference<V> viewRef;

    @Override public void attachView(V view) {
        viewRef = new WeakReference<V>(view);
    }

    /**
     * 获取持有的View
     * 注意：需要自己在detachView里取消后台操作，否则会导致NullPointerException
     *
     * @return <code>null</code>, if view is not attached, otherwise the concrete view instance
     */
    public V getView() {
        return viewRef == null ? null : viewRef.get();
    }

    /**
     * Checks if a view is attached to this presenter. You should always call this method before
     * calling {@link #getView()} to get the view instance.
     */
    public boolean isViewAttached() {
        return viewRef != null && viewRef.get() != null;
    }

    @Override public void detachView(boolean retainInstance) {
        if(mCompositeSubscription!=null){
            mCompositeSubscription.unsubscribe();
        }
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }
}
